﻿#include <vf_tcpserver.h>

namespace VFAdapter {

MyTcpServer::MyTcpServer()
    : m_ep(boost::asio::ip::tcp::v4(), 0), m_sock(m_services),
      m_accept(m_services, m_ep), m_rtData{""}, m_timer(m_services) {}

uint16_t MyTcpServer::GetPort() const {
  return m_accept.local_endpoint().port();
}

std::string MyTcpServer::GetReturnData() const { return m_rtData; }

void MyTcpServer::ListenHandler(boost::system::error_code const &ec) {
  if (ec) {
    Stop();
    return;
  }
  memset(m_receiveBuf, 0, sizeof(m_receiveBuf));
  m_sock.async_receive(
      boost::asio::buffer(m_receiveBuf),
      boost::bind(&MyTcpServer::ReadHandler, shared_from_this(),boost::placeholders::_1));
}

void MyTcpServer::ReadHandler(boost::system::error_code const &ec) {
  if (ec) {
    Stop();
    return;
  }
  m_rtData = m_receiveBuf;

  Stop();
}

void MyTcpServer::Stop() {
  m_sock.close();
  m_services.stop();
}

void MyTcpServer::Listen() {
  m_accept.async_accept(
      m_sock, boost::bind(&MyTcpServer::ListenHandler, shared_from_this(), boost::placeholders::_1));

  // 最多等待5分钟
  m_timer.expires_from_now(boost::posix_time::minutes(5));
  m_timer.async_wait(boost::bind(&MyTcpServer::Stop, shared_from_this()));
  m_services.run();
}
boost::shared_ptr<MyTcpServer> MyTcpServer::Create() {
  pointer _ptr(new MyTcpServer());
  return _ptr;
}
} // namespace VFAdapter
